package  com.htd.apm;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htd.htdapmcommon.constants.ErrorCodeConstants;
import com.htd.htdapmdmo.AlarmsInfo;
import com.htd.htdapmservice.dao.LogAnalyzeErrorRecordDao;
import com.htd.htdapmservice.result.CreateAlarmResult;
import com.htd.htdapmservice.service.intf.*;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import com.alibaba.dubbo.config.annotation.Reference;
import com.htd.htdapmapi.alarm.facade.intf.AlarmFacade;
import com.htd.htdapmapi.alarm.request.AlarmInto;
import com.htd.htdapmapi.alarm.result.AlarmResult;
import com.htd.htdapmcommon.enums.AlarmSendStatus;
import com.htd.htdapmcommon.enums.AlarmsLevelEnum;
import com.htd.htdapmcommon.enums.AlarmsStatusEnum;
import com.htd.htdapmdmo.LogAnalyzeErrorRecord;
import com.htd.htdapmdmo.OneAlertAlarmsRecordInfo;
import com.htd.htdapmservice.dao.AlarmsInfoDao;
import com.htd.htdapmservice.dao.DataCompareDao;
import com.htd.htdapmservice.dao.OneAlertAlarmsRecordDao;
import com.htd.htdapmservice.request.SearchAlarmInto;
import com.htd.htdapmservice.service.impl.OneAlertServiceImpl;

/**
 * 测试类
 */
@RestController
public class TestControl {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestControl.class);

    @Autowired
    private OneAlertServiceImpl oneAlertServiceImpl;
    
    @Autowired
    private DataCompareDao dataCompareDao;
   
    @Reference(version = "1.0")
    private AlarmFacade alarmFacade;

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    private TransportClient client;
   
    @RequestMapping(value = "/test")
    public String test(){
        return "当前时间:"+new Date();

    }

    @RequestMapping(value = "/testMail")
    public CreateAlarmResult testMail(@RequestBody AlarmInto alarmInto){
        return oneAlertServiceImpl.sendAlarmInfo(alarmInto);
    }

    @RequestMapping(value = "/testfacade")
    public String testfacade(){
       return "success";
    }
    @Autowired
    private AlarmsInfoDao alarmsInfoDao;
    
    @Autowired 
    private OneAlertAlarmsRecordDao oneAlertAlarmsRecordDao;
    
    
    /**
     * 
     * 测试--认证--接口
     */
    @RequestMapping(value = "/getAuthentication")
    public String getAuthentication(){
	    return "success";
    }
    
    
    /**
     * 
     * 测试--创建告警API--接口
     */
    @RequestMapping(value = "/createAlarmFacade")
    public String createAlarmFacade(){
    	AlarmInto alarmInto=new AlarmInto();
    	alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
    	alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
    	alarmInto.setAlarmsDetail("测试告警接口-yzq");
    	alarmInto.setProductType("PAY");
    	alarmInto.setAlarmsTitle("测试title");
    	AlarmResult alarmResult=alarmFacade.createAlarm(alarmInto);
    	
        return alarmResult.getResponseMsg();
    }

    /**
     * 
     * 查询我的警告
     */
    @RequestMapping(value = "/searchAlarm")
    public String searchAlarm(){
    	SearchAlarmInto searchAlarmInto=new SearchAlarmInto();
    	searchAlarmInto.setStatus("ACTIVE,ACK,CLOSED");
    	oneAlertServiceImpl.searchAlarm(searchAlarmInto);
	    return "success";
    }
    
    /**
     * 
     * 测试批量创建告警
     */
    @RequestMapping(value = "/testBatchCreatAlarms")
    public String testBatchCreatAlarms(){
    	
	    return "success";
    }
    
    /**
     * 
     * 测试修改status的状态为“SEND_YES”
     */
    @RequestMapping(value = "/updateAlarmStatus")
    public String updateAlarmStatus(){
    	Map<String, Object> paramMap = new HashMap<>();
    	Long idLong=(long) 150;
		paramMap.put("id", idLong);
		paramMap.put("status",AlarmSendStatus.SEND_YES.toString());
		dataCompareDao.updateAlarmStatus(paramMap);
    	return "success";
    }
    
    
    /**
	 * "one_alert_alarms_record"中查询出所有status !="ACTIVE"的数据
	 * 
	 */
    @RequestMapping(value = "/getListByStatus")
    public String getListByStatus(){
    	 List<OneAlertAlarmsRecordInfo> oneAlertAlarmsRecordInfoList =new ArrayList<OneAlertAlarmsRecordInfo>();
    	 
    	 oneAlertAlarmsRecordInfoList = oneAlertAlarmsRecordDao.getListByStatus(AlarmsStatusEnum.ACTIVE.getCode());
    	 
    	 alarmsInfoDao.updateAlarmInfoStatus(oneAlertAlarmsRecordInfoList);
    	 
    	 return "success";
    }


    //查询接口
    @GetMapping("/get/bossConsumer")
    public ResponseEntity get(@RequestParam(name = "id", defaultValue = "") String id) {
        if (StringUtils.isEmpty(id)) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        GetResponse response = this.client.prepareGet("boss_consumer-2018.10.21", "boss_consumer", id).get();
        if (!response.isExists()) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(response.getSource(), HttpStatus.OK);
    }

    @PostMapping("/post/bossConsumer/errorMsg")
    public ResponseEntity getMsgError(@RequestParam(name = "date") String date) {
        if (StringUtils.isEmpty(date)) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }

        String indexs = "boss_consumer-"+date;
        String types = "boss_consumer";

        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        boolBuilder.filter(QueryBuilders.matchQuery("message", "Exception"));
        SearchRequestBuilder builder = this.client.prepareSearch(indexs)
                .setTypes(types)
                .setSearchType(SearchType.QUERY_THEN_FETCH)
                .setQuery(boolBuilder)
                .setFrom(0)
                .setSize(10);
        SearchResponse response = builder.get();

        List<Map<String,Object>> result = new ArrayList<>();
        response.getHits().forEach((s)->result.add(s.getSourceAsMap()));
        return new ResponseEntity(result, HttpStatus.OK);
    }

    /**
     * 获取错误信息
     * @param indexs  indexName 和 type
     * @param date    查询时间  yyyy.MM.dd
     * @param hours   查询小时  当前时间到当前的几个小时内
     * @return
     * @throws ParseException
     */
   @PostMapping("/post/getErrorInfo")
   public ResponseEntity getErrorInfo(
           @RequestParam(name = "indexs",required = true) String indexs,
           @RequestParam(name = "date",required = false) String date,
           @RequestParam(name = "hours",required = false,defaultValue = "1") int hours
   ) throws ParseException {
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
       if(StringUtils.isEmpty(date)){
           date = sdf.format(new Date());
       }else{
           date = sdf.format(sdf.parse(date)) ;
       }
       String types = indexs;
       indexs = indexs+"-"+date;

       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
       String endDate = simpleDateFormat.format(new Date());  //当前时间
       Calendar calendar = Calendar.getInstance();
       /* HOUR_OF_DAY 指示一天中的小时 */
       calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hours);
       String beginDate  =simpleDateFormat.format(calendar.getTime()); ;

       BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
//        boolBuilder.filter(QueryBuilders.matchQuery("message", "[ERROR]"));
       boolBuilder.filter(QueryBuilders.matchQuery("message", "Exception"));

       boolBuilder.filter(QueryBuilders.rangeQuery("@timestamp").from(beginDate).to(endDate));
       SearchRequestBuilder builder = this.client.prepareSearch(indexs)
               .setTypes(types)
               .setSearchType(SearchType.QUERY_THEN_FETCH)
               .setQuery(boolBuilder)
               .setFrom(0)
               .setSize(10);
       SearchResponse response = builder.get();

       List<Map<String,Object>> result = new ArrayList<>();
       response.getHits().forEach((s)->result.add(s.getSourceAsMap()));
       return new ResponseEntity(result, HttpStatus.OK);
   }


    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private LogAnalyzeErrorRecordService logAnalyzeErrorRecordService;
    @PostMapping("/post/getLog")
    public ResponseEntity getLog(@RequestParam int id){
       LogAnalyzeErrorRecord logAnalyzeErrorRecord  = logAnalyzeErrorRecordService.findLogAnalyzeErrorRecordById(id);
        return new ResponseEntity(logAnalyzeErrorRecord,HttpStatus.OK);
    }

    @PostMapping("/post/getLogList")
    public ResponseEntity getLogList(@RequestParam String title){
        List<LogAnalyzeErrorRecord> logAnalyzeErrorRecord  = logAnalyzeErrorRecordService.findLogAnalyzeErrorRecordList(title);
        return new ResponseEntity(logAnalyzeErrorRecord,HttpStatus.OK);
    }

    @Autowired
    private OneAlertService oneAlertService;

    @Autowired
    private OneAlertKeyService oneAlertKeyService;
    @GetMapping("/get/getlogAnalyzeErrorRecordTask")
    public ResponseEntity getlogAnalyzeErrorRecordTask(){
        List<LogAnalyzeErrorRecord>  logAnalyzeErrorRecordList = elasticsearchService.getNewLogAnalyzeErrorRecordList();
        try {
            if (logAnalyzeErrorRecordList!=null &&logAnalyzeErrorRecordList.size()>0) {
                for (LogAnalyzeErrorRecord logAnalyzeErrorRecord:logAnalyzeErrorRecordList) {
                    AlarmInto alarmInto = new AlarmInto();
                    alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                    alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                    alarmInto.setProductType(logAnalyzeErrorRecord.getProductTypeCode());
                    alarmInto.setAlarmsDetail(logAnalyzeErrorRecord.getAlarmsDetail());
//                    alarmInto.setAlarmsTitle(ProductCategoryEnum.getValueByCode(logAnalyzeErrorRecord.getProductTypeCode())+"日志异常");
                    alarmInto.setAlarmsTitle(oneAlertKeyService.findOneAlertKeyByProductCode(logAnalyzeErrorRecord.getProductTypeCode()).getProductName()+"日志异常");
                    AlarmResult alarmResult = oneAlertService.createAlarm(alarmInto);
                    if(ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())){
                        logAnalyzeErrorRecord.setSendStatus(AlarmSendStatus.SEND_YES);
                        logAnalyzeErrorRecordService.insertLogAnalyzeErrorRecord(logAnalyzeErrorRecord);
                    }else{
                        logAnalyzeErrorRecordService.insertLogAnalyzeErrorRecord(logAnalyzeErrorRecord);
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("logAnalyzeErrorRecordTask.execute异常：{}",e.getMessage());
        }
        return new ResponseEntity(HttpStatus.OK);
    }

    @Autowired
    private LogAnalyzeErrorRecordDao logAnalyzeErrorRecordDao;

    @GetMapping("/get/logErrorAlarmTask")
    public ResponseEntity getlogErrorAlarmTask(){
        List<LogAnalyzeErrorRecord> logAnalyzeErrorRecordList = logAnalyzeErrorRecordDao.findLogAnalyzeErrorRecordListByStatus(AlarmSendStatus.SEND_NO.getCode());
        try {
            if (logAnalyzeErrorRecordList!=null &&logAnalyzeErrorRecordList.size()>0) {
                for (LogAnalyzeErrorRecord logAnalyzeErrorRecord : logAnalyzeErrorRecordList) {
                    AlarmInto alarmInto = new AlarmInto();
                    alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                    alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                    alarmInto.setProductType(logAnalyzeErrorRecord.getProductTypeCode());
                    alarmInto.setAlarmsDetail(logAnalyzeErrorRecord.getAlarmsDetail());
//                    alarmInto.setAlarmsTitle(ProductCategoryEnum.getValueByCode(logAnalyzeErrorRecord.getProductTypeCode())+"日志异常");
                    alarmInto.setAlarmsTitle(oneAlertKeyService.findOneAlertKeyByProductCode(logAnalyzeErrorRecord.getProductTypeCode()).getProductName()+"日志异常");
                    AlarmResult alarmResult = oneAlertService.createAlarm(alarmInto);
                    if(ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())){
                        logAnalyzeErrorRecord.setSendStatus(AlarmSendStatus.SEND_YES);
                        logAnalyzeErrorRecord.setUpdateTime(new Date());
                        logAnalyzeErrorRecordDao.updateLogAnalyzeErrorRecordById(logAnalyzeErrorRecord);
                    }
                }
            }
        }catch (Exception e) {
            LOGGER.error("LogErrorAlarmTask execute error", e);
        }
        return new ResponseEntity(HttpStatus.OK);
    }
    @Autowired
    private AlarmsInfoService alarmsInfoService;

    @GetMapping("/get/getalarmsInfoTask")
    public ResponseEntity getalarmsInfoTask(){
        List<AlarmsInfo>  alarmsInfoList = alarmsInfoService.getAlarmsInfoListBySendStatus(AlarmSendStatus.SEND_NO.getCode());
        try {
            if (alarmsInfoList!=null &&alarmsInfoList.size()>0) {
                AlarmInto alarmInto  =null;
                for (AlarmsInfo alarmsInfo:alarmsInfoList) {
                    alarmInto= new AlarmInto();
                    alarmInto.setEventType(AlarmsStatusEnum.ALARM_TRIGGER.getCode());
                    alarmInto.setPriority(AlarmsLevelEnum.LEVEL_TWO.getCode());
                    alarmInto.setProductType(alarmsInfo.getAlarmsProductTypeCode());
                    alarmInto.setAlarmsDetail(alarmsInfo.getAlarmsDetail());
                    alarmInto.setAlarmsTitle(alarmsInfo.getAlarmsTitle());
                    AlarmResult alarmResult = alarmsInfoService.createAlarm(alarmInto);
                    if(ErrorCodeConstants.SUCCESS_CODE.equals(alarmResult.getResponseCode())){
                        Map<String,Object> map = new HashMap<String,Object>();
                        map.put("sendStatus",AlarmSendStatus.SEND_YES);
                        map.put("alarmsId",alarmsInfo.getAlarmsId());
                        map.put("updateTime",new Date());
                        alarmsInfoService.updateSendStatusByAlarmsId(map);
                    }
                }
            }
        }catch (Exception e){
            LOGGER.error("alarmsInfoTask.execute异常：{}",e.getMessage());
        }
        return new ResponseEntity(HttpStatus.OK);
    }
}
